/* eslint-disable no-undef */
/* eslint-disable prefer-promise-reject-errors */

import store from '@store'
import Utils from '@utils'
import _ from 'lodash'
import MyServer from '@api'
const discardList = [
  'logistics-product-manage',
  'services-channels'
]
const formatRouterTree = (data) => { // 权限列表动态生成路由表
  const parents = data.filter(p => p.pid === '0')
  const children = data.filter(c => c.pid !== '0')
  dataTotree(parents, children)
  return parents
}

const dataTotree = (parents, children) => { // 生成router树
  parents.map((p) => {
    children.map((c, i) => {
      if (c.pid === p.id) {
        const _c = JSON.parse(JSON.stringify(children))
        _c.splice(1, i)
        dataTotree([c], _c)// 递归
        if (p.children) {
          if (!p.children.some((item) => item.id === c.id)) {
            p.children.push(c)
          }
        } else {
          p.children = [c]
        }
      }
    })
  })
}
const secondList = []
const generateRoutes = (userRoutes) => { // 生成路由
  return userRoutes.map((r, key) => {
    const path = r.path.split('/').filter(item => {
      return item
    })
    const name = Utils.KebabChangeCamel(path[0], '-')// 根据path转驼峰命名
    const linkPath = store.getters.menuList.filter((l) => {
      return l.id === r.pid
    })

    let pathLink = ''
    if (r.pid === '0') {
      pathLink = r.path
    }
    if (linkPath.length > 0) {
      if (Number(r.level) === 3) {
        const parentTopPth = store.getters.menuList.filter((l) => {
          return l.id === linkPath[0].pid
        })
        if (parentTopPth.length > 0) {
          pathLink = parentTopPth[0].path + '/' + linkPath[0].path + '/' + r.path
        } else {
          pathLink = linkPath[0].path + '/' + r.path
        }
      } else {
        pathLink = linkPath[0].path + '/' + r.path
      }
    }
    const detailState = !!r.path.match(RegExp(/detail/))// 详情不在菜单上展示

    const routes = {
      path: r.path,
      link: pathLink,
      level: r.level,
      id: r.id,
      pid: r.pid,
      name: Utils.firstUpperCase(name), // 首字母大写
      meta: {
        title: r.title,
        icon: r.icon,
        keepAlive: !detailState
      },
      hidden: detailState
    }
    if (r.children) {
      if (r.level > 1) { // 二级下拉主菜单
        routes.redirect = routes.path
        routes.component = resolve => require([`@/views${pathLink}`], resolve)
      } else { // 一级下拉主菜单
        routes.component = resolve => require(['@/views/layout/index.vue'], resolve)
        routes.redirect = r.path + '/' + r.children[0].path
        routes.meta.icon = r.icon ? r.icon : 'home_icon'
      }
      routes.children = generateRoutes(r.children)
    } else { // 落地页面
      if (Number(r.pid) === 0 && Number(r.level) === 1 && (r.children === undefined || r.children.length === 0)) { // 一级菜单
        routes.meta.icon = r.icon ? r.icon : 'home_icon'
        routes.component = resolve => require([`@/views/${path[0]}/index.vue`], resolve)
      } else { // 二级\三级
        const flag = discardList.some((p) => {
          return p === r.path
        })

        const pathUrl = flag ? pathLink + '/index.vue' : pathLink

        routes.component = resolve => require([`@/views${pathUrl}`], resolve)
      }
    }
    return routes
  })
}

const state = {
  menuList: [], // 路由
  beforeNewRoutes: [], // 动态生成的组件路由
  newRoutes: [] // 动态生成的组件路由
}

const mutations = {
  SET_MENULIST: (state, routes) => {
    state.menuList = routes
  },
  SET_NEWROUTES: (state, routes) => {
    state.newRoutes = routes
  },
  SET_BEFORENEWROUTES: (state, routes) => {
    state.beforeNewRoutes = routes
  }
}

const actions = {
  async createNewRoutes ({ commit, state }) { // 生成组件路由
    await store.dispatch('permission/getMenu')

    const menuList = formatRouterTree(state.menuList)

    const newRoutes = generateRoutes(menuList)
    newRoutes.map((item) => {
      if (Number(item.pid) === 0 && (item.children === undefined || item.children.length === 0)) {
        //
        item.link = 'index'
        item.redirect = `/${item.path}/index`
      }
    })
    commit('SET_BEFORENEWROUTES', newRoutes)

    const topMenu = []
    const noOnlyTopChildren = newRoutes.filter((item) => {
      let flag = true
      menuList.map((item1) => {
        if (item1.id === item.id && Number(item1.pid) === 0 && (item.children === undefined || item.children.length === 0)) {
          flag = false

          const child = JSON.parse(JSON.stringify(item))
          child.component = item.component

          child.link = 'index'
          child.path = 'index'

          topMenu.push({
            path: item.path,
            component: resolve => require(['@views/layout/index.vue'], resolve),
            redirect: '/' + item.path + '/index',
            hidden: false,
            children: [child],
            meta: {
              title: item.title,
              icon: item.icon ? item.icon : 'home_icon'
            }
          })
        }
      })
      if (flag) {
        return item
      }
    })


    const allRotues = noOnlyTopChildren.concat(topMenu)


    commit('SET_NEWROUTES', allRotues)
    return allRotues
  },
  getMenu ({ commit, state }) {
    const userRoutes = require('../../../static/menu.json')
    commit('SET_MENULIST', userRoutes.data)
    // MyServer.user
    //   .getMenu({
    //     data: { id: 'ies' }
    //   })
    //   .then(res => {
    //     if (!res) {
    //       return reject('验证失败，请重新登录.')
    //     }
    //     commit('SET_MENULIST', res)
    //   })
  },
  resetNewRoutes ({ commit, state }) { // 清空权限路由
    commit('SET_MENULIST', [])
    commit('SET_NEWROUTES', [])
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
